<template>
  <div class="device-management">
    <el-row :gutter="20">
      <el-col :span="6">
        <el-card shadow="hover" class="device-card">
          <template #header>
            <div class="card-header">
              <span>设备总数</span>
            </div>
          </template>
          <div class="device-stat">
            <el-statistic :value="deviceStats.total">
              <template #title>
                <div style="display: inline-flex; align-items: center">
                  在线设备
                  <el-tag size="small" type="success" style="margin-left: 8px">
                    {{ deviceStats.online }}台
                  </el-tag>
                </div>
              </template>
            </el-statistic>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="device-card">
          <template #header>
            <div class="card-header">
              <span>设备状态</span>
            </div>
          </template>
          <div class="device-stat">
            <el-progress
              type="dashboard"
              :percentage="deviceStats.onlineRate"
              :color="deviceStats.onlineRate > 80 ? '#67C23A' : '#E6A23C'"
            >
              <template #default="{ percentage }">
                <span class="progress-label">{{ percentage }}%</span>
                <span class="progress-text">在线率</span>
              </template>
            </el-progress>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="device-card">
          <template #header>
            <div class="card-header">
              <span>能耗统计</span>
            </div>
          </template>
          <div class="device-stat">
            <el-statistic :value="deviceStats.totalPower" suffix="kW">
              <template #title>
                <div style="display: inline-flex; align-items: center">
                  总功率
                  <el-tag size="small" type="warning" style="margin-left: 8px">
                    {{ deviceStats.activeDevices }}台运行中
                  </el-tag>
                </div>
              </template>
            </el-statistic>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="device-card">
          <template #header>
            <div class="card-header">
              <span>设备类型</span>
            </div>
          </template>
          <div class="device-stat">
            <el-statistic :value="deviceStats.types.length">
              <template #title>
                <div style="display: inline-flex; align-items: center">
                  类型数量
                  <el-tag size="small" type="info" style="margin-left: 8px">
                    共{{ deviceStats.totalTypes }}种
                  </el-tag>
                </div>
              </template>
            </el-statistic>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-card shadow="hover" class="device-list">
      <template #header>
        <div class="card-header">
          <span>设备列表</span>
          <div class="header-actions">
            <el-input
              v-model="searchQuery"
              placeholder="搜索设备"
              style="width: 200px; margin-right: 10px"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
            <el-button type="primary" @click="handleAddDevice">
              <el-icon><Plus /></el-icon>添加设备
            </el-button>
          </div>
        </div>
      </template>

      <el-table :data="filteredDevices" style="width: 100%">
        <el-table-column prop="name" label="设备名称" />
        <el-table-column prop="type" label="类型" />
        <el-table-column prop="location" label="位置" />
        <el-table-column prop="status" label="状态">
          <template #default="{ row }">
            <el-tag :type="row.status === 'online' ? 'success' : 'danger'">
              {{ row.status === 'online' ? '在线' : '离线' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="power" label="功率">
          <template #default="{ row }">
            {{ row.power }}kW
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="{ row }">
            <el-button-group>
              <el-button size="small" @click="handleEdit(row)">编辑</el-button>
              <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 设备编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加设备' : '编辑设备'"
      width="500px"
    >
      <el-form :model="deviceForm" label-width="100px">
        <el-form-item label="设备名称">
          <el-input v-model="deviceForm.name" />
        </el-form-item>
        <el-form-item label="设备类型">
          <el-select v-model="deviceForm.type" placeholder="选择类型">
            <el-option label="空调" value="aircon" />
            <el-option label="照明" value="light" />
            <el-option label="通风" value="ventilation" />
          </el-select>
        </el-form-item>
        <el-form-item label="位置">
          <el-input v-model="deviceForm.location" />
        </el-form-item>
        <el-form-item label="功率">
          <el-input-number v-model="deviceForm.power" :min="0" :step="0.1" />
        </el-form-item>
        <el-form-item label="状态">
          <el-switch
            v-model="deviceForm.status"
            :active-value="'online'"
            :inactive-value="'offline'"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSave">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { Plus, Search } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'

interface Device {
  id: number
  name: string
  type: string
  location: string
  status: 'online' | 'offline'
  power: number
}

interface DeviceStats {
  total: number
  online: number
  onlineRate: number
  totalPower: number
  activeDevices: number
  types: string[]
  totalTypes: number
}

const devices = ref<Device[]>([
  {
    id: 1,
    name: '空调主机1',
    type: 'aircon',
    location: '实验室1',
    status: 'online',
    power: 2.5
  },
  {
    id: 2,
    name: '照明系统1',
    type: 'light',
    location: '实验室2',
    status: 'online',
    power: 1.2
  }
])

const deviceStats = computed<DeviceStats>(() => {
  const online = devices.value.filter(d => d.status === 'online').length
  const total = devices.value.length
  const types = [...new Set(devices.value.map(d => d.type))]
  const totalPower = devices.value.reduce((sum, d) => sum + d.power, 0)
  const activeDevices = devices.value.filter(d => d.status === 'online').length

  return {
    total,
    online,
    onlineRate: Math.round((online / total) * 100),
    totalPower,
    activeDevices,
    types,
    totalTypes: types.length
  }
})

const searchQuery = ref('')
const filteredDevices = computed(() => {
  if (!searchQuery.value) return devices.value
  const query = searchQuery.value.toLowerCase()
  return devices.value.filter(device =>
    device.name.toLowerCase().includes(query) ||
    device.type.toLowerCase().includes(query) ||
    device.location.toLowerCase().includes(query)
  )
})

const dialogVisible = ref(false)
const dialogType = ref<'add' | 'edit'>('add')
const deviceForm = ref<Partial<Device>>({
  name: '',
  type: '',
  location: '',
  status: 'online',
  power: 0
})

const handleAddDevice = () => {
  dialogType.value = 'add'
  deviceForm.value = {
    name: '',
    type: '',
    location: '',
    status: 'online',
    power: 0
  }
  dialogVisible.value = true
}

const handleEdit = (row: Device) => {
  dialogType.value = 'edit'
  deviceForm.value = { ...row }
  dialogVisible.value = true
}

const handleDelete = (row: Device) => {
  ElMessageBox.confirm(
    '确定要删除这个设备吗？',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    devices.value = devices.value.filter(item => item.id !== row.id)
    ElMessage.success('删除成功')
  })
}

const handleSave = () => {
  if (dialogType.value === 'add') {
    devices.value.push({
      id: Date.now(),
      ...deviceForm.value
    } as Device)
  } else {
    const index = devices.value.findIndex(item => item.id === deviceForm.value.id)
    if (index !== -1) {
      devices.value[index] = {
        ...devices.value[index],
        ...deviceForm.value
      } as Device
    }
  }
  dialogVisible.value = false
  ElMessage.success(dialogType.value === 'add' ? '添加成功' : '更新成功')
}
</script>

<style scoped>
.device-management {
  padding: 20px;
}

.device-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.device-stat {
  text-align: center;
  padding: 10px 0;
}

.progress-label {
  font-size: 24px;
  font-weight: bold;
}

.progress-text {
  display: block;
  font-size: 14px;
  color: #666;
}

.header-actions {
  display: flex;
  align-items: center;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style> 